package com.yaofeng.mybatis.shiro;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yaofeng.mybatis.jwt.JWTToken;
import com.yaofeng.mybatis.modules.sys.entity.User;
import com.yaofeng.mybatis.modules.sys.entity.UserToken;
import com.yaofeng.mybatis.modules.sys.service.IUserService;
import com.yaofeng.mybatis.modules.sys.service.IUserTokenService;
import com.yaofeng.mybatis.util.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 *  shiro配置了匿名登录就不会走MyRealm认证和授权
 *  SpringBoot+Shiro引起事务失效、错误原因、解决方法 https://blog.csdn.net/finalcola/article/details/81197584
 *  在Realm中Service声明上加入@Lazy注解，延迟Realm实现中Service对象的初始化时间，
 *  这样就可以保证Service实际初始化的时候会被BeanPostProcessor拦截，创建具有事务功能的代理对象
 * Created by yaofeng on 2019/8/15.
 */

@Service
public class MyRealm  extends AuthorizingRealm {


    @Autowired
    @Lazy
    private IUserService iUserService;

    @Autowired
    @Lazy
    private IUserTokenService  iUserTokenService;



    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 授权
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
       /* String username = JWTUtil.getUsername(principals.toString());
        TbUser user = userService.getOne(new QueryWrapper<TbUser>().eq("username",username));
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("admin");
        Set<String> permission = new HashSet<>(Arrays.asList("edit","view"));
        simpleAuthorizationInfo.addStringPermissions(permission);
        // 将当前用户/角色/权限信息放入session
        return simpleAuthorizationInfo;*/
       return   new SimpleAuthorizationInfo();
    }

    /**
     * 认证
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        //  判断token是否已经作废 列如用户退出原先token还在有效期内就作废处理
        UserToken  userToken  = iUserTokenService.getOne(Wrappers.<UserToken>lambdaQuery().eq(UserToken::getTokenValue,token));
        if(userToken!=null){
            throw new AuthenticationException("token has expired and is no longer valid!");
        }

        // 解密获得loginName，用于和数据库进行对比
        String loginName = JWTUtil.getLoginName(token);
        if (loginName == null) {
            throw new AuthenticationException("token Invalid!");
        }

        User user = iUserService.getOne(new QueryWrapper<User>().lambda().eq(User::getLoginName,loginName));
        if (user == null) {
            throw new AuthenticationException("account does not exist!");
        }

        if (! JWTUtil.verify(token, loginName, user.getUserPassword())) {
            throw new AuthenticationException("token has expired and is no longer valid!");
        }

        return new SimpleAuthenticationInfo(token, token, "my_realm");
    }
}
